package vincent.com.layouttest.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import vincent.com.layouttest.R;
import vincent.com.layouttest.util.LogUtil;

/**
 * Created by zhengwenchen on 2017/1/5.
 */

public class SystemVolumeLevelView extends View {
    private AudioManager audioManager;
    private boolean mAttached = false;
    private boolean isInited = false;
    private int mCurrentVolume = 0;

    private Bitmap volumeIcon;
    private Paint txtPaint;

    private int mMiddleOffset = 0;

    private Rect txtRect = new Rect();

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(!isInited)
                return;

            String action = intent.getAction();
            if("android.media.VOLUME_CHANGED_ACTION".equals(action)){

                mCurrentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) ;// 当前的媒体音量
                Log.i("czw_volume", "音量变化--->" + mCurrentVolume);

//                requestLayout();
//                ViewCompat.postInvalidateOnAnimation(SystemVolumeLevelView.this);
                postInvalidate();
            }
        }
    };

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int totalHeight = 0;
        int totalWidth = 0;

        int leftPadding = getPaddingLeft();
        int topPadding = getPaddingTop();
        int rightPadding = getPaddingRight();
        int bottomPadding = getPaddingBottom();

        String volueNum = String.valueOf(mCurrentVolume);
        txtPaint.getTextBounds(volueNum, 0, volueNum.length(), txtRect);
        txtPaint.setTextAlign(Paint.Align.CENTER);

        totalWidth += leftPadding;
        totalWidth += rightPadding;

        totalHeight += topPadding;
        totalHeight += bottomPadding;

        totalWidth += txtRect.width();

        if(volumeIcon != null){
            totalWidth += volumeIcon.getWidth();
            totalWidth += mMiddleOffset;
            totalHeight += Math.max(volumeIcon.getHeight(), txtRect.height());
        }else{
            totalHeight += txtRect.height();
        }

        LogUtil.i("czw", "SystemVolumeLevel w: " + totalWidth + " | h: " + totalHeight);
        setMeasuredDimension(totalWidth, totalHeight);
    }

    public void setVolume(int volume){
        this.mCurrentVolume = volume;
//        requestLayout();

//        ViewCompat.postInvalidateOnAnimation(this);
        postInvalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {

//        canvas.drawARGB(255, 30, 103, 171);
        int leftPadding = getPaddingLeft();

        int txtStartX = txtRect.width()/2;
        int txtStartY = 0;

        if(volumeIcon != null){
            int left = leftPadding;
            int top = (getMeasuredHeight() - volumeIcon.getHeight())/2;
            canvas.drawBitmap(volumeIcon, left, top, null);
            txtStartX += volumeIcon.getWidth() + mMiddleOffset + leftPadding;
        }

        txtStartY = (getMeasuredHeight() - txtRect.height())/2 + txtRect.height();

        String volumeLevel = String.valueOf(mCurrentVolume);

        canvas.drawText(volumeLevel, txtStartX, txtStartY, txtPaint);
    }

    public SystemVolumeLevelView(Context context) {
        this(context, null);
    }

    public SystemVolumeLevelView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SystemVolumeLevelView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init(){
        audioManager = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);
        volumeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.p2_system_volume);

        txtPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        txtPaint.setColor(Color.WHITE);

        int size = getResources().getDimensionPixelSize(R.dimen.system_icon_txt_size);
        txtPaint.setTextSize(size);
        Typeface font = Typeface.create("sans-serif-condensed", Typeface.BOLD);
        txtPaint.setTypeface(font);

        mCurrentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

        mMiddleOffset = getResources().getDimensionPixelSize(R.dimen.system_icon_txt_offset);

        isInited = true;
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        if(!mAttached){
            mAttached = true;
            IntentFilter filter = new IntentFilter();
            filter.addAction("android.media.VOLUME_CHANGED_ACTION");

            getContext().registerReceiver(mReceiver, filter);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();

        if(mAttached){
            getContext().unregisterReceiver(mReceiver);
            mAttached = false;
        }
    }
}
